from collections import OrderedDict

from goods.models import GoodsChannel


def get_goods_category():
    """
    商品频道及分类菜单
    使用有序字典保存类别的顺序
    categories = {
        1: { # 组1
            'channels': 一级分类[{'id':频道编号, 'name':频道名称, 'url':频道链接},{}, {}...],
            'sub_cats': 二级分类[{'id':, 'name':, 'sub_cats':[{},{}]}, {}, {}, ..]
        },
        2: { # 组2

        }
    }
    示例:
    {
        (1,
              {'channels': [{'id': 1, 'name': '手机', 'url': 'http://shouji.jd.com'},
                            {'id': 2, 'name': '相机', 'url': 'http://www.itcast.cn'},
                            {'id': 3, 'name': '数码', 'url': 'http://www.itcast.cn'}],
               'sub_cats': [<GoodsCategory: 手机通讯>,
                            <GoodsCategory: 手机配件>,
                            <GoodsCategory: 摄影摄像>,
                            <GoodsCategory: 数码配件>,
                            <GoodsCategory: 影音娱乐>,
                            <GoodsCategory: 智能设备>,
                            <GoodsCategory: 电子教育>]
              }
        ),
        ....
    }
    """
    # 这里采用有序字典
    categories = OrderedDict()
    # 按组号和组内顺序排序
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    # print(channels)

    for channel in channels:
        # print(repr(channel))  # <GoodsChannel: 手机>
        # 初始化分类
        group_id = channel.group_id  # 当前组的组号
        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}
        # 添加一级分类
        categories[group_id]['channels'].append({
            'id': channel.id,
            'name': channel.category.name,  # 当前频道所属类别的名称
            'url': channel.url
        })
        # print(repr(channel.category))  # <GoodsCategory: 手机>
        # print(repr(channel.category.goodscategory_set.all()))  # <QuerySet [<GoodsCategory: 手机通讯>, <GoodsCategory: 手机配件>]>
        # 这里channel.category.goodscategory_set是一级分类下的二级分类
        # 添加二级分类
        sub_cats = channel.category.goodscategory_set.all()
        for sub2 in sub_cats:
            # 添加三级分类,原本二级分类sub2没有sub_cats属性,这里是定义赋值
            sub2.sub_cats = sub2.goodscategory_set.all()
            # print(sub2.sub_cats)  # <QuerySet [<GoodsCategory: 手机>, <GoodsCategory: 游戏手机>, <GoodsCategory: 老人机>, <GoodsCategory: 对讲机>]>
            # print('*'*50)
            categories[channel.group_id]['sub_cats'].append(sub2)

    return categories
